﻿namespace NorthernLights
{
    using System;
    using System.IO;
    using System.Runtime.Serialization.Json;
    using System.Text;

    /// <summary>
    /// Serializer class.
    /// </summary>
    public class Serializer
    {
        /// <summary>
        /// Serialize object.
        /// </summary>
        /// <typeparam name="T">Object type to serialize.</typeparam>
        /// <param name="obj">Object to serialize</param>
        /// <returns>The JSON string or null on error.</returns>
        public static string WriteFromObject<T>(T obj)
        {
            if (obj == null)
            {
                return null;
            }

            string result = null;

            try
            {
                DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));

                using (MemoryStream ms = new MemoryStream())
                {
                    ser.WriteObject(ms, obj);
                    result = Encoding.UTF8.GetString(ms.ToArray(), 0, ms.ToArray().Length);
                }
            }
            catch (Exception ex)
            {
                DebugLogger.Instance.Write(ex);
            }

            return result;
        }

        /// <summary>
        /// Deserialize JSON string.
        /// </summary>
        /// <typeparam name="T">Object to deserialize to.</typeparam>
        /// <param name="json">The input json string.</param>
        /// <returns>The object value or default(T) on error.</returns>
        public static T ReadToObject<T>(string json)
        {
            if (string.IsNullOrEmpty(json))
            {
                return default(T);
            }

            T deserialized = default(T);

            try
            {
                DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));

                using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json)))
                {
                    deserialized = (T)ser.ReadObject(ms);
                }
            }
            catch (Exception ex)
            {
                DebugLogger.Instance.Write(ex);
            }

            return deserialized;
        }
    }
}
